package com.solocredit.finance.ui.steps.act

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.DensityUtils
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaCameraSelfieBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.steps.impl.MullaUploadPresenterImpl
import com.solocredit.finance.ui.steps.view.IMullaUploadView
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.imagecovert.ImageConvert
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/12 17:12
 * @Annotation：自拍照
 */
class MullaCameraSelfieAct: MvpAct<IMullaUploadView, MullaUploadPresenterImpl>(),IMullaUploadView {
    private var _binding: ActMullaCameraSelfieBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "camera ocr binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""

    override fun createPresenter(): MullaUploadPresenterImpl {
        return MullaUploadPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        _binding = ActMullaCameraSelfieBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        _binding?.titleLayout?.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        initCameraScale()
        startCamera()

        _binding?.ivLanguage?.visibility = View.GONE
        if (MullaConfigs.isTanz()){
            _binding?.ivLanguage?.visibility = View.VISIBLE
        }
    }

    override fun initMullaListener() {
        _binding?.imgBack?.setOnClickListener {
            finish()
        }

        //客服
        _binding?.imgKefu?.setOnClickListener {
            showMullaKefuDialog("SelfieCamera Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"SelfieCamera Page")
        }

        //语言切换
        _binding?.ivLanguage?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"SelfieCamera Page")
            showMullaLanguageDialog("SelfieCamera Page", onSelectCallback = {
            })
        }

        //拍照
        _binding?.imgTakeCamera?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CAMERA_TAKE_PHOTO,"SelfieCamera Page")
            takeFilePhoto()
        }

        //重拍
        _binding?.remakeLayout?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_SELFIE_REMAKE,"")
            showTakeView()
        }

        //使用
        _binding?.usePhotoLayout?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_SELFIE_USE_PHOTO, imgUsePath)
            showMullaLoading(isTOuchOut = false, isCancel = false)
            // 图片处理
            ImageConvert.covert(context = this, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    MullaLog.e("imageConvert success>>>>>>>$localPath")
                    presenter.onMullaUploadImageAction(localPath)
                }
            }
        }
    }

    override fun initMullaData() {
        _binding?.let { binding ->
            //牌照信息
            val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
            if (licenseInfo == null){
                binding.licenseLayout.visibility = View.GONE
            } else {
                binding.licenseLayout.visibility = View.VISIBLE
                ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
                binding.textLicenseDesc.text = licenseInfo.optString("desc")
                binding.textLicenseValue.text = licenseInfo.optString("companyName")
            }
        }
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                .build()
                .also {
                    it.setSurfaceProvider(_binding?.cameraView?.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 设置相机画面和拍照预览View的宽高和位置
     */
    private fun initCameraScale(){
        // 确保 PreviewView 的布局参数设置为 4:3
        _binding?.cameraView?.post {
            val width = MyApp.app.getPhoneWidth() - DensityUtils.dp2px(100f)
            val layoutParams = _binding?.cameraView?.layoutParams
            layoutParams?.width = width
            layoutParams?.height = width
            _binding?.cameraView?.layoutParams = layoutParams

            _binding?.cameraView?.y = ((MyApp.app.getPhoneHeight() - width) / 3).toFloat()
        }

        _binding?.imgPreview?.post {
            val width = MyApp.app.getPhoneWidth() - DensityUtils.dp2px(100f)
            val layoutParams = _binding?.imgPreview?.layoutParams
            layoutParams?.width = width
            layoutParams?.height = width
            _binding?.imgPreview?.layoutParams = layoutParams

            _binding?.imgPreview?.y = ((MyApp.app.getPhoneHeight() - width) / 3).toFloat()
        }
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = MyApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    imgUri?.path?.let {
                        MullaLog.e("take photo complete>>>>>>>${it}")
                        imgUsePath = it
                    }
                    showCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    MullaLog.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        _binding?.let { binding ->
            binding.imgPreview.visibility = View.GONE
            binding.imgTakeCamera.visibility = View.VISIBLE
            binding.remakeLayout.visibility = View.INVISIBLE
            binding.usePhotoLayout.visibility = View.INVISIBLE
        }
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        _binding?.let { binding ->
            ImageUtil.instance?.loadImageUrl(this@MullaCameraSelfieAct,binding.imgPreview,imgUsePath,0)
            binding.imgPreview.visibility = View.VISIBLE
            binding.imgTakeCamera.visibility = View.INVISIBLE
            binding.remakeLayout.visibility = View.VISIBLE
            binding.usePhotoLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 图片上传完成
     */
    override fun showMullaUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgUsePath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_SELFIE_CAMERA_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_SELFIE_CAMERA_END)
        if (::cameraExecutor.isInitialized){
            cameraExecutor.shutdown()
        }
    }
}